<?php

namespace app\api\Service;

use think\Db;
use think\Config;
use app\common\library\Auth;

class CollectService
{
    // 管家收藏列表
    public static function getStewardLists($data)
    {
        $auth = Auth::instance();
        $user_id = $auth->id;
        $limit = isset($data['limit'])? $data['limit'] : 10;

        $list = \app\admin\model\StewardCollect::where(['user_id'=>$user_id])->order('createtime desc')->field('steward_id')->paginate($limit);
        foreach ($list as $k => $item){
            $steward = \app\admin\model\Steward::where(['id'=>$item['steward_id']])->field('id,avatar,realname,gender,age,forte')->find();

            if($steward){
                $item['avatar'] = $steward['avatar'];
                $item['realname'] = $steward['realname'];
                $item['gender'] = $steward['gender'];
                $item['age'] = $steward['age'];
                $item['forte'] = explode(',', $steward['forte']);
            }else{
                unset($list[$k]);
            }
        }

        return ['code'=>1,'msg'=>'查询成功','data'=>$list];
    }

    // 新增收藏管家
    public static function stewardAdd($data)
    {
        $auth = Auth::instance();
        $user_id = $auth->id;
        $steward_id = $data['steward_id'];

        $steward = \app\admin\model\Steward::where(['id'=>$steward_id])->find();
        if(!$steward){
            return ['code'=>0,'msg'=>'管家不存在','data'=>''];
        }

        $exist = \app\admin\model\StewardCollect::where(['user_id'=>$user_id,'steward_id'=>$steward_id])->value('id');
        if($exist){
            return ['code'=>0,'msg'=>'不要重复收藏','data'=>''];
        }
        $result = \app\admin\model\StewardCollect::create(['user_id'=>$user_id,'steward_id'=>$steward_id]);
        if($result){
            return ['code'=>1,'msg'=>'操作成功','data'=>''];
        }
        return ['code'=>0,'msg'=>'操作失败','data'=>''];
    }

    // 删除收藏管家
    public static function stewardDel($data)
    {
        $auth = Auth::instance();
        $user_id = $auth->id;
        $steward_id = $data['steward_id'];

        $exist = \app\admin\model\StewardCollect::where(['user_id'=>$user_id,'steward_id'=>$steward_id])->value('id');
        if(!$exist){
            return ['code'=>0,'msg'=>'收藏不存在','data'=>''];
        }
        $result = \app\admin\model\StewardCollect::where(['user_id'=>$user_id,'steward_id'=>$steward_id])->delete();
        if($result){
            return ['code'=>1,'msg'=>'操作成功','data'=>''];
        }
        return ['code'=>0,'msg'=>'操作失败','data'=>''];
    }
}